#from sourenfe.qzone.models import *
#from sourenfe.msn.models import *
from django.shortcuts import render_to_response
from django.template import Context, loader, Template, RequestContext
from django.http import HttpResponse

import simplejson
import string
import MySQLdb
import datetime

from lib.config import *
from lib.utils import *
from lib.search import *
from lib.pages import *
#from lib.snippet import *
from sourenfe.qzone.models import *
import re
from string import join


def index(request, adv=None):
    UID, needset = get_cookie_id(request)
    page_head = renderHead()
    page_foot = renderFoot()

    page = renderIndex(firsttry = (True if needset else False), adv = adv)
    #response = HttpResponse(page.render(c), mimetype="text/html,application/xhtml+xml,application/xml")
    response = HttpResponse(renderZhaorenme(page_head, page_foot, page), mimetype='text/html')
    if needset:
        # avoid caching for the very first visit only
        response = avoid_refresh_dup(response)
        response.set_cookie('UID', UID, expires=needset)
    return response

def plain(request, type):
    adv = None
    UID, needset = get_cookie_id(request)
    page_head = renderHead(needinfo=False)
    page_foot = renderFoot()

    page = renderPlain(type)
    response = HttpResponse(renderZhaorenme(page_head, page_foot, page), mimetype='text/html')
    if needset:
        # avoid caching for the very first visit only
        response = avoid_refresh_dup(response)
        response.set_cookie('UID', UID, expires=needset)
    return response

def feedback(request):
    if request.POST:
        ftype = int(request.POST['ftype'])
        content = request.POST['content']
        contact = request.POST['contact']
        UID, needset = get_cookie_id(request)
        IP = get_real_ip(request)
        modtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # connect MySQL server
        try:
            conn = MySQLdb.connect (host = DB_HOST,
                                    user = DB_USER,
                                    passwd = DB_PASSWD,
                                    db = "feedback")
            # perform a insert
            cursor = conn.cursor()
            cursor.execute ("INSERT INTO info (ip,cookieid,ftype,contact,content,modtime) VALUES('%s','%s',%d,'%s','%s','%s');" %(IP,UID,ftype,contact,content,modtime))
            cursor.close()

        except MySQLdb.Error, e:
            print "Error %d:%s" %(e.args[0], e.args[1])
            sys.exit(1)
        #close connection
        conn.commit()
        conn.close()

    UID, needset = get_cookie_id(request)
    page_head = renderHead(needinfo=False)
    page_foot = renderFoot()
    page = renderFeedback(request)
    response = HttpResponse(renderZhaorenme(page_head, page_foot, page), mimetype='text/html')
    if needset:
        # avoid caching for the very first visit only
        response = avoid_refresh_dup(response)
        response.set_cookie('UID', UID, expires=needset)
    return response

def search(request, type, query, pagenum=1, clickseq=0, sex=0, age=0, province=0, city=0, marriage=0):
#    u = user.objects.filter(uid='404347528')[0]
#    response = HttpResponse(u.uName, mimetype='text/html')
#    response.encoding = 'utf-8'
#    return response
    UID, needset = get_cookie_id(request)

    keywords = sanitizeQueryWords(query)
    pagenum=int(pagenum)
    clickseq=int(clickseq)
    sex=int(sex)
    age=int(age)
    province=int(province)
    city=int(city)
    marriage=int(marriage)
    pagetype='qzone' # specify a page type
    res = searchit(string.join(keywords, " "), sex=sex, age=age, province=province, city=city, marriage=marriage, offset=((pagenum-1)*SEARCH_PAGE_SIZE), type=type, host=SE_HOST)
    #return HttpResponse(str(res), mimetype='text/html')
    #r = ""
    usercells = []
    uids = []
    seqs = []
    first_blog_seqs = []
    blogs = []
    matchednum = []
    onlinestatus = []
    if type == "qzone":
        if res and res.has_key('matches'):
            for u in res['matches']:
                seqs.append(int(u['attrs']['authorseq']))
                first_blog_seqs.append(int(u['id']))
                matchednum.append(int(u['attrs']['@count']))
                onlinestatus.append(int(u['attrs']['onlinestatus']))
            users = user.getArrBySeq(seqs)
            blogs = blog.getArrBySeq(first_blog_seqs)
            for u in users:
                uids.append(u.uid)
            profiles = profile.getArrByUid(uids)
            userpies = userpie.getArrByUid(uids)
            for number, u in enumerate(users):
                #userpies = userpie.objects.filter(uid=u.uid)
                #ublogs = blog.objects.filter(authorid=u.uid)
                p = profiles[number]
                renderedQzoneCell = renderQzoneCell(u, p, blogs[number], userpies[u.uid], number, keywords, matchedarticleNum=matchednum[number], rank=number, onlinestatus=onlinestatus[number])
                usercells.append(renderedQzoneCell)
    elif type == "msn":
        if res and res.has_key('matches'):
            for i,u in enumerate(res['matches']):
                seqs.append(int(u['attrs']['authorseq']))
                first_blog_seqs.append(int(u['id']))
                matchednum.append(int(u['attrs']['@count']))
            from sourenfe.msn.models import *
            users = user.getArrBySeq1(seqs)
            blogs = blog.getArrBySeq1(first_blog_seqs)
            for u in users:
                uids.append(u.uid)
            userpies = userpie.getArrByUid1(uids)
            for number,u in enumerate(users):
                usercells.append(renderMsnCell(u, blogs[number], userpies[u.uid] ,number, keywords, matchedarticleNum=matchednum[number], rank=number))
     

    first_url = ''
    prev_url = ''
    last_url = ''
    last_url = ''

    page = loader.get_template('search.html')
    c = Context({ 'usercells': usercells,
		  'uids': uids,
		  'seqs': seqs,
		  'uids_str': string.join(uids, ", "),
		  'type': type,
		  'keywords': keywords,
		  'ks': join(keywords, " "),
		  'pagenum': pagenum,
		  'clickseq': clickseq,
		  'sex': sex,
		  'province': province,
		  'city': city,
		  'marriage': marriage,
		  'pagesize': SEARCH_PAGE_SIZE,
		  'total_found': res['total_found'] if res else 0,
		  'pagecount': (res['total']/SEARCH_PAGE_SIZE) if res else 1,
		  'time': res['time'] if (res and res.has_key('time')) else '',
          'pagetype': type,
    })

    #page_head = " "
    page_head = renderHead(pagetype=type)
    page_foot = renderFoot(type = 1)
    response = HttpResponse(renderZhaorenme(page_head, page_foot, page.render(c)), mimetype='text/html')
    if needset:
        response = avoid_refresh_dup(response)
        response.set_cookie('UID', UID, expires=needset)

    response.encoding = 'utf-8'
    #response = avoid_refresh_dup(response)
    #if type == 'qzone':
    #    return response
    return response

def searchname(request, type, name):
    pass

def detail(request, type, id, ks=None, rank = None, clickseq = None):
    # 'keywords': "-_-_",
    h404 = HttpResponse('this is a 404')
    
    if type ==  'qzone':
        usr = user.objects.get(uid=int(id))
        try:
            prf = profile.objects.get(uin=id) # uin is a CharField
        except:
            prf = None
        blogs = blog.objects.filter(authorid=usr.uid)
        pie = userpie.objects.filter(uid=int(id))
        # pie items
        
        pie_data = []
        for p in pie:
            pblogids = p.blog_ids.split('@@')
            pweights = len(pblogids)
            pkeyword = p.keywords.split('@@')
  
            dataobj = {
                'id'      : p.cat_id,
                'name'    : p.cat_name,
                'blogids' : pblogids,
                'weight'  : pweights,
                'keywords': pkeyword,
            }
            pie_data.append(dataobj)
        # sort pie data on weights
        pie_data.sort(key=lambda i: i['weight'], reverse=True)

        # trend items
        from calendar import timegm # use timegm to generate js timestamp for flot.js. details in flot.js API.txt
        def _get_jsstamp(timeobj):
            return timegm(timeobj.timetuple())*1000

        blog_trends = []
        for cat in pie_data: # need a better solution
            raw = [_get_jsstamp(b.time) for b in blogs if b.cat_id == cat['id']]
            data = []
            for item in set(raw):
                data.append((item, raw.count(item)))

            blog_trends.append({
                'label' : cat['name'],
                'data'  : data,
                'color' : cat['id'], # color set to cat_id
            })

        # construct blog items
        blogitems = [{
            'title' : i.title,
            'time'  : i.time,
            'num_comment' : i.num_comment,
            'num_read'    : i.num_read,
            'cat_id'      : i.cat_id,
            'cat_name'    : i.cat_name,
            'blog_id'     : i.blog_id,
        } for i in blogs]

        result = {
            # basic items
            'uName' : usr.uName,
            'uid' : usr.uid,
            'nickname' : prf.nickname if prf else "",
            'authorid' : id,
            'total'    : usr.articleNum,
            'age'      : prf.age if prf else "",
            'birthday' : prf.birthday if prf else "",
            'country'  : prf.country if prf else "",
            'province' : prf.province if prf else "",
            'city'     : prf.city if prf else "",
            'career'   : prf.career if prf else "",
            'sex'      : prf.sex if prf else "",
            'marriage' : prf.marriage if prf else "",
            'type'     : type,

            # pie/chart items
            'pie_data_js' : simplejson.dumps(pie_data, sort_keys=True),

            # trend items
            'blog_trends_js' : simplejson.dumps(blog_trends),
            'mint_js' : _get_jsstamp(min(blogs, key=lambda b: b.time).time),
            'maxt_js' : _get_jsstamp(max(blogs, key=lambda b: b.time).time),

            # blog items
            'blogitems' : blogitems,           
			}

        page = loader.get_template('detail_qzone.html')
        c = Context(result)
        page_head = renderHead(needinfo = False, pagetype='qzone')
        page_foot = renderFoot(type = 1)
        response = HttpResponse(renderZhaorenme(page_head, page_foot, page.render(c)), mimetype='text/html')
        #return render_to_response('detail_qzone.html', result)
        return response
    else:
        return h404


def article(request, type, uid, blogid):
    uid = int(uid)
    blogid = int(blogid)
    u = user.objects.filter(uid=uid)
    if u:
        u = u[0]
        b = blog.objects.filter(blog_id=blogid, authorid=uid)
        if b:
            b = b[0]
        else:
          return HttpResponse('No Blog ID')
    else:
      return HttpResponse('No User ID')

    page_head = renderHead(needinfo = False)
    page_foot = renderFoot(type = 1)
    page = loader.get_template('article.html')
    c = Context({ 'hostuin': uid,
        'uName': u.uName,
        'qzonedescription': u.qzoneDescription,
        'qzonename': u.qzoneName,
        'title': b.title,
        'time': b.time,
        'cat_name': b.cat_name,
        'num_comment': b.num_comment,
        'num_read': b.num_read,
        'content': b.content,
    })
    page = page.render(c)
    response = HttpResponse(renderZhaorenme(page_head, page_foot, page), mimetype='text/html')

    #if needset:
    #    response = avoid_refresh_dup(response)
    #    response.set_cookie('UID', UID, expires=needset)
    response.encoding = 'utf-8'
    return response
